package controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bizlogic.User;

import model.EmployeeDTO;

import dao.DAOException;

/**
 * Servlet implementation class UserLoginController
 */
@WebServlet("/UserLoginController")
public class UserLoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserLoginController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			authentication(request, response);
		} catch (DAOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void authentication(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			DAOException {
		RequestDispatcher rd = null;
		User users = new User();

		String forwardTo = "/Error.html";
		
		String u = request.getParameter("userName");
		String p = request.getParameter("password");

		EmployeeDTO user = users.Authenticate(u, p);

		if (user.getEmployeeID() > 0) {

			HttpSession session = request.getSession(true);
			session.setAttribute("user", user);

			String designation = user.getDesignation().trim();

			if (designation.equals("Managers"))
				forwardTo = "/LeaveHistoryServlet";

			else if (designation.equals("Staff"))
				forwardTo = "/claimcompformJSP.jsp";
					//forwardTo = "/StaffHandlerController";

			else if (designation.equals("Admins"))
				forwardTo = "/claimcompformJSP.jsp";
					//forwardTo = "/StaffHandlerController";

			else
				forwardTo = "/Login.jsp";

		} 
//		else
//				forwardTo = "/Login.jsp";

		rd = request.getRequestDispatcher(forwardTo);
		rd.forward(request, response);

	}

}
